﻿using LikeBangumi.Pages;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Graphics.Display;
using Windows.System.Display;
using Windows.UI;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;

//“空白页”项模板在 http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409 上有介绍

namespace LikeBangumi
{
    public enum BangumiType
    {
        Bilibili = 0,
        Dilidili = 1,
        Tucao = 2,
        Fengche = 3,
        Acfun=4,
        Local=5

    }
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class MainPage : Page
    {
       
        public MainPage()
        {
            this.InitializeComponent();
            menu_List.SelectedIndex = 0;
            SystemNavigationManager.GetForCurrentView().BackRequested += MainPage_BackRequested;
            SetTheme();
        }
        SettingHelper settings = new SettingHelper();
        private void SetTheme()
        {
            if (!settings.SettingContains("Theme"))
            {
                settings.SetSettingValue("Theme","Light");
            }
            if ((string)settings.GetSettingValue("Theme") == "Light")
            {
                txt_Light.Text = "夜间模式";
                font_Light.Glyph = "\uE708";
                this.RequestedTheme = ElementTheme.Light;
            }
            else
            {
                txt_Light.Text = "日间模式";
                font_Light.Glyph = "\uE706";
                this.RequestedTheme = ElementTheme.Dark;
            }
            ChangeTitbarColor();
        }

        //string _NavigationState = string.Empty;
        private void ChangeTitbarColor()
        {
            if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
            {
                // StatusBar.GetForCurrentView().HideAsync();
                StatusBar statusBar = StatusBar.GetForCurrentView();
                statusBar.ForegroundColor = Colors.Gray;
                statusBar.BackgroundColor = ((SolidColorBrush)Grid_Top.Background).Color;
                statusBar.BackgroundOpacity = 100;
            }
            ////电脑标题栏颜色
            //var titleBar = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().TitleBar;
            //titleBar.BackgroundColor = ((SolidColorBrush)Grid_Top.Background).Color;
            //titleBar.ForegroundColor = Color.FromArgb(255, 254, 254, 254);//Colors.White纯白用不了。。。
            //titleBar.ButtonHoverBackgroundColor =Colors.Gray;
            //titleBar.ButtonBackgroundColor = ((SolidColorBrush)Grid_Top.Background).Color;
            //titleBar.ButtonForegroundColor = Color.FromArgb(255, 254, 254, 254);
            //titleBar.InactiveBackgroundColor = ((SolidColorBrush)Grid_Top.Background).Color;
            //titleBar.ButtonInactiveBackgroundColor = ((SolidColorBrush)Grid_Top.Background).Color;
            
        }

        bool IsClicks = false;
        private async void MainPage_BackRequested(object sender, BackRequestedEventArgs e)
        {
           
            if (playFrame.Content!=null)
            {
                playFrame.Content = null;
                if (dispRequest != null)
                {
                    dispRequest = null;
                }
                DisplayInformation.AutoRotationPreferences = DisplayOrientations.None;
                e.Handled = true;
                return;
            }
            if (detailFrame.CanGoBack)
            {
                detailFrame.GoBack();
                e.Handled = true;
                return; 
            }
            else
            {
                if (detailFrame.Content!=null)
                {
                    detailFrame.Content = null;
                    detailFrame.SetNavigationState("1,0");
                    SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
                    e.Handled = true;
                }
                else
                {
                    if (e.Handled == false)
                    {
                        if (IsClicks)
                        {
                            Application.Current.Exit();
                        }
                        else
                        {
                            IsClicks = true;
                            e.Handled = true;
                            messShow.Show("再按一次退出程序", 3000);
                            await Task.Delay(3000);
                            IsClicks = false;

                        }
                    }
                    SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
                }
               // e.Handled = true;
               // return;
            }

           

        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            //_NavigationState = detailFrame.GetNavigationState();
            SettingHelper strring = new SettingHelper();

            if (!strring.SettingContains("GG1030"))
            {
                var dialog = new MessageDialog(@"七月番来啦，快去找找有没有你喜欢的番剧吧

视频播放失败可以在设置中尝试打开、关闭FFMpeg
如果觉得好用，可以给我打赏瓶凉茶喝哦，支付婊：2500655055@qq.com,**程", "更新内容");
                dialog.Commands.Add(new UICommand("确定", cmd => { }, commandId: 0));
                dialog.Commands.Add(new UICommand("不再提醒", cmd =>
                {
                    strring.SetSettingValue("GG1030", "Yes");
                }, commandId: 1));
                dialog.ShowAsync();

            }

            ChangeTitbarColor();
        }

        private void btn_Menu_Click(object sender, RoutedEventArgs e)
        {
          
            if (sp_view.IsPaneOpen)
            {
                sp_view.IsPaneOpen = false;
            }
            else
            {
                sp_view.IsPaneOpen = true;
            }
        }

        private void Menu_List_Buttom_ItemClick(object sender, ItemClickEventArgs e)
        {
            if ((e.ClickedItem as StackPanel).Tag.ToString() == "Light")
            {
                if (txt_Light.Text== "夜间模式")
                {
                    txt_Light.Text = "日间模式";
                    font_Light.Glyph = "\uE706";
                    this.RequestedTheme = ElementTheme.Dark;
                    settings.SetSettingValue("Theme", "Dark");
                }
                else
                {
                    txt_Light.Text = "夜间模式";
                    font_Light.Glyph = "\uE708";
                    this.RequestedTheme = ElementTheme.Light;
                    settings.SetSettingValue("Theme", "Light");
                }
                ChangeTitbarColor();
            }
            else
            {
                detailFrame.Navigate(typeof(SettingPage));
            }
            sp_view.IsPaneOpen = false;
        }

        private void seachBox_Top_LostFocus(object sender, RoutedEventArgs e)
        {
            grid_Seach.Visibility = Visibility.Visible;
            seachBox_Top.Visibility = Visibility.Collapsed;
        }

        private void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            grid_Seach.Visibility = Visibility.Collapsed;
            seachBox_Top.Visibility = Visibility.Visible;
            seachBox_Top.Focus( FocusState.Keyboard);
        }
        bool PageChnageEventReged = false;
        bool OpenTagEventReged = false;
        bool DiliPageChnageEventReged = false;
        bool DiliPlayEventReged = false;
        bool FCPageChnageEventReged = false;
        bool MyPageChnageEventReged = false;
        bool DownChnageEventReged = false;
        private void menu_List_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            
            if (this.ActualWidth < 800)
            {
                detailFrame.Content = null;
                detailFrame.SetNavigationState("1,0");
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
            }
            switch (menu_List.SelectedIndex)
            {
                case 0:
                    masterFrame.Navigate(typeof(MyselfPage));
                    if (!MyPageChnageEventReged)
                    {
                        (masterFrame.Content as MyselfPage).PageChnageEvent += new MyselfPage.PageChnage((MyBangumi my) => {
                            switch (my.Type)
                            {
                                case 1:
                                    detailFrame.Navigate(typeof(BiliInfoPage),my.Info);
                                    break;
                                case 2:
                                    detailFrame.Navigate(typeof(DiliInfo), my.Info);
                                    break;
                                case 3:
                                    detailFrame.Navigate(typeof(FCInfoPage), my.Info);
                                    break;
                                default:
                                    break;
                            }
                            
                        });
                        MyPageChnageEventReged = true;
                    }
                  
                    txt_title.Text = "我的追番";
                    break;
                case 1:
                    masterFrame.Navigate(typeof(ACPage));
                    txt_title.Text = "Acfun";
                    break;
                case 2:
                    masterFrame.Navigate(typeof(BiliPage));
                    if (!PageChnageEventReged)
                    {
                        (masterFrame.Content as BiliPage).PageChnageEvent += new BiliPage.PageChnage((BangumiType type, string a) =>
                        {
                            detailFrame.Navigate(typeof(BiliInfoPage), a);
                        });
                        PageChnageEventReged = true;
                    }
                    if (!OpenTagEventReged)
                    {
                        (masterFrame.Content as BiliPage).OpenTagEvent += new BiliPage.OpenTag((string[] a) =>
                        {
                            detailFrame.Navigate(typeof(BiliTagInfoPage), a);
                        });
                        OpenTagEventReged = true;
                    }
                    txt_title.Text = "哔哩哔哩";
                    break;
                case 3:
                    masterFrame.Navigate(typeof(DiliPage));
                    if (!DiliPageChnageEventReged)
                    {
                        (masterFrame.Content as DiliPage).PageChnageEvent += new DiliPage.PageChnage((BangumiType type, string a) => {
                            detailFrame.Navigate(typeof(DiliInfo), a);
                        });
                        DiliPageChnageEventReged = true;
                    }
                    if (!DiliPlayEventReged)
                    {
                        (masterFrame.Content as DiliPage).PlayEvent += new DiliPage.PageChnage((BangumiType type, string a) => {
                            playFrame.Navigate(typeof(PlayerPage), new PlayModel() { info = a,type= type});
                            if (dispRequest == null)
                            {
                                // 用户观看视频，需要保持屏幕的点亮状态
                                dispRequest = new DisplayRequest();
                                dispRequest.RequestActive(); // 激活显示请求
                            }
                            DisplayInformation.AutoRotationPreferences = (DisplayOrientations)5;
                        });
                        DiliPlayEventReged = true;
                    }
                    txt_title.Text = "嘀哩嘀哩";
                    break;
                case 4:
                    masterFrame.Navigate(typeof(FCPage));
                    if (!FCPageChnageEventReged)
                    {
                        (masterFrame.Content as FCPage).PageChnageEvent += new FCPage.PageChnage((BangumiType type, string a) => {
                            detailFrame.Navigate(typeof(FCInfoPage), a);
                        });
                        FCPageChnageEventReged = true;
                    }
                    txt_title.Text = "风车动漫";
                    break;
                case 5:
                    //masterFrame.Navigate(typeof(FCPage));
                    //if (!FCPageChnageEventReged)
                    //{
                    //    (masterFrame.Content as FCPage).PageChnageEvent += new FCPage.PageChnage((BangumiType type, string a) => {
                    //        detailFrame.Navigate(typeof(FCInfoPage), a);
                    //    });
                    //    FCPageChnageEventReged = true;
                    //}
                    txt_title.Text = "吐槽弹幕网";
                    break;
                case 6:
                    masterFrame.Navigate(typeof(DownloadPage));
                    if (!DownChnageEventReged)
                    {

                        (masterFrame.Content as DownloadPage).playEvent += new DownloadPage.PlayVideo((PlayModel model) => {
                            playFrame.Navigate(typeof(PlayerPage), model);
                            if (dispRequest == null)
                            {
                                // 用户观看视频，需要保持屏幕的点亮状态
                                dispRequest = new DisplayRequest();
                                dispRequest.RequestActive(); // 激活显示请求
                            }
                            DisplayInformation.AutoRotationPreferences = (DisplayOrientations)5;
                        });
                        FCPageChnageEventReged = true;
                    }
                    txt_title.Text = "离线管理";
                    break;
                default:
                    break;
            }
          
            sp_view.IsPaneOpen = false;
        }


        private DisplayRequest dispRequest = null;
        bool regPlay = false;
        bool regPlay_D = false;
        bool regPlay_F = false;
        private void detailFrame_Navigated(object sender, NavigationEventArgs e)
        {
            //{ms-appx:///Pages/BlankPage.xaml}

            if (detailFrame.Content!= null)
            {
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
                if ((detailFrame.Content as Page).Tag!=null)
                {
                    switch ((detailFrame.Content as Page).Tag.ToString())
                    {
                        case "Bili":
                            if (!regPlay)
                            {
                                (detailFrame.Content as BiliInfoPage).playEvent += new BiliInfoPage.PlayVideo((PlayModel model) => {

                                    playFrame.Navigate(typeof(PlayerPage), model);
                                    if (dispRequest == null)
                                    {
                                        // 用户观看视频，需要保持屏幕的点亮状态
                                        dispRequest = new DisplayRequest();
                                        dispRequest.RequestActive(); // 激活显示请求
                                    }
                                    DisplayInformation.AutoRotationPreferences = (DisplayOrientations)5;
                                });
                                regPlay = true;
                            }
                           
                            break;
                        case "Dili":
                            if (!regPlay_D)
                            {
                                (detailFrame.Content as DiliInfo).playEvent += new DiliInfo.PlayVideo((PlayModel model) =>
                                {
                                    playFrame.Navigate(typeof(PlayerPage), model);
                                    if (dispRequest == null)
                                    {
                                        // 用户观看视频，需要保持屏幕的点亮状态
                                        dispRequest = new DisplayRequest();
                                        dispRequest.RequestActive(); // 激活显示请求
                                    }
                                    DisplayInformation.AutoRotationPreferences = (DisplayOrientations)5;
                                });
                                regPlay_D = true;
                            }
                            break;
                        case "FC":
                            if (!regPlay_F)
                            {
                                (detailFrame.Content as FCInfoPage).playEvent += new FCInfoPage.PlayVideo((PlayModel model) => {
                                    playFrame.Navigate(typeof(PlayerPage), model);
                                    if (dispRequest == null)
                                    {
                                        // 用户观看视频，需要保持屏幕的点亮状态
                                        dispRequest = new DisplayRequest();
                                        dispRequest.RequestActive(); // 激活显示请求
                                    }
                                    DisplayInformation.AutoRotationPreferences = (DisplayOrientations)5;
                                });
                                regPlay_F = true;
                            }
                          
                            break;
                        default:
                            break;
                    }
                }
            }
            else
            {
                if (!detailFrame.CanGoBack)
                {
                    SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
                }
            }

        }

        private async void Page_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (!settings.SettingContains("HideTitleBar"))
            {
                settings.SetSettingValue("HideTitleBar", true);
            }
            ApplicationView av = ApplicationView.GetForCurrentView();

            switch (av.Orientation)
            {
                case ApplicationViewOrientation.Landscape:
                    if ((bool)settings.GetSettingValue("HideTitleBar"))
                    {
                        if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent(typeof(StatusBar).ToString()))
                        {
                            StatusBar statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
                            await statusBar.HideAsync();
                        }
                    }
                    break;
                case ApplicationViewOrientation.Portrait:
                    if (Windows.Foundation.Metadata.ApiInformation.IsTypePresent(typeof(StatusBar).ToString()))
                    {
                        StatusBar statusBar = Windows.UI.ViewManagement.StatusBar.GetForCurrentView();
                        await statusBar.ShowAsync();
                    }
                    break;
                default:
                    break;
            }


            if (this.ActualWidth>=800)
            {
                column1.Width = new GridLength(0.6, GridUnitType.Star);
                Grid.SetColumn(detailFrame,1);
                ImageBrush img = new ImageBrush();
                img.ImageSource = new BitmapImage(new Uri("ms-appx:///Assets/未标题-1.png"));
                img.Stretch = Stretch.None;
                detailFrame.Background = img;
                masterFrame.BorderThickness = new Thickness(0, 0, 1, 0);
            }
            else
            {
                column1.Width = new GridLength(0, GridUnitType.Pixel);
                Grid.SetColumn(detailFrame, 0);
                detailFrame.Background = null;
                masterFrame.BorderThickness = new Thickness(0, 0, 0, 0);
            }
        }

        private void playFrame_Navigated(object sender, NavigationEventArgs e)
        {
            if (playFrame.Content != null)
            {
                SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Visible;
            }
        }

        private void masterFrame_Navigated(object sender, NavigationEventArgs e)
        {
           
        }

    }
}
